package com.ee.chat.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ee.chat.api.service.IPayNotifyService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.*;
import com.ee.chat.common.entity.*;
import com.ee.chat.common.service.IGeneralService;
import com.ee.chat.common.service.IPayService;
import com.ee.chat.common.service.IYieldService;
import com.ndhutu.ee.util.pay.Notify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author shane
 * @version 1.0.0
 * @Date 2021/1/26 15:58
 */
@Service
public class PayNotifyServiceImpl implements IPayNotifyService, Notify {
    private Logger log = LoggerFactory.getLogger(PayNotifyServiceImpl.class);

    @Resource
    UserVipMapper userVipMapper;
    @Resource
    UserRechargeLogMapper userRechargeLogMapper;
    @Resource
    SysOrderMapper sysOrderMapper;
    @Resource
    HostMapper hostMapper;
    @Resource
    UserWithdrawLogMapper userWithdrawLogMapper;
    @Resource
    UserVipLogMapper userVipLogMapper;
    @Resource
    VipConfigMapper vipConfigMapper;
    @Resource
    IYieldService yieldService;
    @Resource
    IGeneralService generalService;
    @Resource
    IPayService payService;
    @Resource
    PayChannelConfigMapper payChannelConfigMapper;
    @Resource
    UserSetMapper userSetMapper;

    @Value("${spring.profiles.active}")
    String active;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String wxPayNotify(HttpServletRequest request) throws Exception {
        log.info("微信支付回调开始-----------------");

        String result = payService.notifyHandle(request, 2, null, this);

        log.info("微信支付回调成功结束-----------------");

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String aliPayNotify(HttpServletRequest request) throws Exception {
        log.info("支付宝支付回调开始-----------------");

        String result = payService.notifyHandle(request, 1, null, this);

        log.info("支付宝支付回调成功结束-----------------");

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result applePayNotify(String token, String receipt, String orderNumber) throws Exception {
        log.info("apple支付回调开始-----------------");

        String result = payService.notifyHandle(null, 3, receipt, this);

        log.info("apple支付回调成功结束-----------------");

        return JSONObject.parseObject(result, Result.class);
    }

    @Override
    public String zfpaiPayNotify(HttpServletRequest request) throws Exception {
        log.info("支付派支付回调开始-----------------");

        String result = payService.notifyHandle(request, 100, null, this);

        log.info("支付派支付回调成功结束-----------------");

        return result;
    }

    @Override
    public String yfkPayNotify(HttpServletRequest request) throws Exception {
        log.info("云支付支付回调开始-----------------");

        String result = payService.notifyHandle(request, 101, null, this);

        log.info("云支付支付回调成功结束-----------------");

        return result;
    }

    @Override
    public String zunPayNotify(HttpServletRequest request) throws Exception {
        log.info("尊付支付回调开始-----------------");

        String result = payService.notifyHandle(request, 102, null, this);

        log.info("尊付支付回调成功结束-----------------");

        return result;
    }

    @Override
    public String pay96Notify(HttpServletRequest request) throws Exception {
        log.info("96支付回调开始-----------------");

        String result = payService.notifyHandle(request, 103, null, this);

        log.info("96支付回调成功结束-----------------");

        return result;
    }

    @Override
    public String fylPayNotify(HttpServletRequest request) throws Exception {
        log.info("付易来支付回调开始-----------------");

        String result = payService.notifyHandle(request, 104, null, this);

        log.info("付易来支付回调成功结束-----------------");

        return result;
    }

    /**
     * 统一回调
     * @Author Shane
     * @Date 2019/10/5 4:57
     * @param orderNumber   订单号
     * @param amount    订单金额(分)
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleNotify(String orderNumber, Integer amount) throws Exception {
        SysOrder order = sysOrderMapper.selectByOrderNumber(orderNumber);
        if(order == null){
            log.info("回调不存在的订单，订单号："+orderNumber);
            throw new Exception();
        }
        if(order.getStatus() == 1){
            log.info("订单号"+orderNumber+"的订单重复回调");
            throw new Exception();
        }
        if("pord".equals(active)){
            if(order.getUndulateAmount() == 0){
                if(!amount.equals(order.getAmount())){
                    log.info("回调金额有误");
                    throw new Exception();
                }
            }else{
                if(!amount.equals(order.getUndulateAmount())){
                    log.info("回调金额有误");
                    throw new Exception();
                }
            }
        }

        //-------------------------------------金币充值begin-------------------------------------------
        if(order.getType() == 0){
            //更新充值记录
            UserRechargeLog userRechargeLog = userRechargeLogMapper.selectByOrderNumber(orderNumber);
            userRechargeLog.setStatus(1);
            userRechargeLog.setUpdateTime(new Date());
            userRechargeLogMapper.updateById(userRechargeLog);

            //更新钱包
            yieldService.updateUserWallet(userRechargeLog.getUserId(), userRechargeLog.getId(), 0, userRechargeLog.getCoin().doubleValue(), "金币充值", 0);

            //处理推广收益
            yieldService.handlePopYield(userRechargeLog.getUserId(), 0, userRechargeLog.getAmount().doubleValue(), userRechargeLog.getId());

            //处理活动收益
            yieldService.handleActivityYield(userRechargeLog.getUserId(), userRechargeLog.getId(), 0, new Date());

            //添加用户动态
            Host host = hostMapper.selectByUserId(order.getUserId());
            UserOperationLog userOperationLog = new UserOperationLog(order.getUserId(), host == null ? 0 : 1, 3, null, userRechargeLog.getId());
            generalService.addUserOperationLog(userOperationLog, null);
        }
        //-------------------------------------金币充值end-------------------------------------------

        //-------------------------------------积分提现begin-------------------------------------------
        if(order.getType() == 1){
            //更新提现记录
            UserWithdrawLog userWithdrawLog = userWithdrawLogMapper.selectByOrderNumber(orderNumber);
            userWithdrawLog.setStatus(1);
            userWithdrawLog.setUpdateTime(new Date());
            userWithdrawLogMapper.updateById(userWithdrawLog);
        }
        //-------------------------------------积分提现end-------------------------------------------

        //-------------------------------------会员购买begin-------------------------------------------
        if(order.getType() == 2){
            //更新购买记录
            UserVipLog userVipLog = userVipLogMapper.selectByOrderNumber(orderNumber);
            userVipLog.setStatus(1);
            userVipLog.setUpdateTime(new Date());
            userVipLogMapper.updateById(userVipLog);

            //更新会员状态
            VipConfig vipConfig = vipConfigMapper.selectById(userVipLog.getVipId());
            UserVip userVip = userVipMapper.getByUserId(userVipLog.getUserId());

            LocalDateTime beginTime = LocalDateTime.now();
            LocalDateTime endTime = beginTime.plusMonths(vipConfig.getValidMonth());

            if(userVip == null){
                userVip = new UserVip(userVipLog.getUserId(), vipConfig.getIdentity(), beginTime, endTime);
                userVipMapper.insert(userVip);
            }else{
                if(vipConfig.getIdentity() > userVip.getIdentity()){
                    userVip.setIdentity(vipConfig.getIdentity());
                    userVip.setBeginTime(beginTime);
                    userVip.setEndTime(endTime);
                }else if(vipConfig.getIdentity().equals(userVip.getIdentity())){
                    if(userVip.getEndTime().isAfter(LocalDateTime.now())){
                        endTime = userVip.getEndTime().plusMonths(vipConfig.getValidMonth());
                        userVip.setEndTime(endTime);
                    }else{
                        userVip.setBeginTime(beginTime);
                        userVip.setEndTime(endTime);
                    }
                }else{
                    if(userVip.getEndTime().isAfter(LocalDateTime.now())){
                        endTime = userVip.getEndTime().plusMonths(vipConfig.getValidMonth());
                        userVip.setEndTime(endTime);
                    }else{
                        userVip.setIdentity(vipConfig.getIdentity());
                        userVip.setBeginTime(beginTime);
                        userVip.setEndTime(endTime);
                    }
                }
                userVipMapper.updateById(userVip);
            }

            //赠送金币，更新钱包
            yieldService.updateUserWallet(userVipLog.getUserId(), userVipLog.getId(), 5, vipConfig.getCoin().doubleValue(), "充值会员赠送", 0);

            //处理推广收益
            yieldService.handlePopYield(userVipLog.getUserId(), 2, userVipLog.getAmount().doubleValue(), userVipLog.getId());

        }
        //-------------------------------------会员购买end-------------------------------------------

        //更新用户支付渠道信息
        if(order.getType() == 0 || order.getType() == 2){
            //更新用户支付渠道
            boolean flag = false;
            UserSet userSet = userSetMapper.selectByUserId(order.getUserId());
            if(userSet == null){
                userSet = new UserSet();
                userSet.setUserId(order.getUserId());
            }
            PayChannelConfig payChannelConfig = payChannelConfigMapper.selectById(order.getPayChannelConfigId());
            if(payChannelConfig.getChannelId() == 1){   //支付宝
                if(!payChannelConfig.getId().equals(userSet.getAliPay())){
                    userSet.setAliPay(payChannelConfig.getId());
                    flag = true;
                }
            }else if(payChannelConfig.getChannelId() == 2){ //微信
                if(!payChannelConfig.getId().equals(userSet.getWxPay())){
                    userSet.setWxPay(payChannelConfig.getId());
                    flag = true;
                }
            }

            if(flag){
                if(userSet.getId() != null){
                    userSetMapper.updateById(userSet);
                }else{
                    userSetMapper.insert(userSet);
                }
            }
        }

        //更新系统订单
        order.setStatus(1);
        order.setUpdateTime(new Date());
        sysOrderMapper.updateById(order);
    }
}
